package drds.common.db.xml_mapping.builder.xml;

import drds.common.ShouldNeverHappenException;
import drds.common.db.xml_mapping.io.Resources;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;


public class XmlMapperEntityResolver implements EntityResolver {


  private static final String MYBATIS_CONFIG_SYSTEM = "mybatis-3-configuration.dtd";
  private static final String MYBATIS_MAPPER_SYSTEM = "mybatis-3-mapper.dtd";

  private static final String MYBATIS_CONFIG_DTD = "drds/common/db/xml_mapping/builder/xml/mybatis-3-config.dtd";
  private static final String MYBATIS_MAPPER_DTD = "drds/common/db/xml_mapping/builder/xml/mybatis-3-mapper.dtd";

  /**
   * Converts a public DTD into a local one.
   */
  @Override
  public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
    String lowerCaseSystemId = systemId.toLowerCase(Locale.ENGLISH);
    if (lowerCaseSystemId.contains(MYBATIS_CONFIG_SYSTEM)) {
      return getInputSource(MYBATIS_CONFIG_DTD, publicId, systemId);
    } else if (lowerCaseSystemId.contains(MYBATIS_MAPPER_SYSTEM)) {
      return getInputSource(MYBATIS_MAPPER_DTD, publicId, systemId);
    } else {
      throw new ShouldNeverHappenException();
    }
  }

  private InputSource getInputSource(String path, String publicId, String systemId) {
    InputSource inputSource = null;
    if (path != null) {
      try {
        InputStream inputStream = Resources.getResourceAsStream(path);
        inputSource = new InputSource(inputStream);
        inputSource.setPublicId(publicId);
        inputSource.setSystemId(systemId);
      } catch (IOException e) {
        // ignore, null is ok
      }
    }
    return inputSource;
  }

}
